from django.shortcuts import render
from . import models
from . import serializers
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class user_add(APIView):
    """
    post:
        添加更新数据
        cname:客户端名称
        fraction：分数
    get:
        获取排名
        cname
    """

    def post(self, request):
        try:
            cname=request.POST['cname']
            fraction=request.POST['fraction']
            #判断数据格式是否正确
            if fraction>0 and isinstance(fraction,int):
                client=models.clientranking.objects.get_or_create(name=cname)
                #判断是否第一录入数据，否则添加历史数据
                if client[1]:
                    client[0].fraction=fraction
                    client[0].save()
                else:
                    client[0].fraction = fraction
                    client[0].save()
                    models.historyfraction.objects.create(operate=client[0],hfraction=client[0].fraction)
                res_data={'result':'ok','message': '数据更新成功！'}
                return Response(res_data,status.HTTP_201_CREATED )
            else:
                res_data = {'result': 'error', 'message': '数据格式错误！'}
                return Response(res_data, status.HTTP_400_BAD_REQUEST)
        except:
            res_data={'result':'error','message': '数据更新失败！'}
            return Response(res_data,status.HTTP_400_BAD_REQUEST )



    def get(self, request):
        try:
            cname=request.GET['cname']
            start=int(request.GET['start'])
            end=int(request.GET['end'])
            client=models.clientranking.objects.all()[start-1:end]
            clientlist=serializers.clientrankingSerializers(client,many=True).data
            #添加排名
            clientlists=list(map(ranklist,clientlist,range(start-1,end)))
            #添加客户端自己排名
            user=models.clientranking.objects.get(name=cname)
            num=models.clientranking.objects.filter(fraction__gt=user.fraction).count()
            clientlists.append({'name':user.name,'fraction':user.fraction,'排名':num+1})

            res_data={'result':'ok','message': '查询成功！','data':clientlists}
            return Response(res_data,status.status.HTTP_200_OK )
        except:
            res_data={'result':'error','message': '查询失败！'}
            return Response(res_data,status.HTTP_400_BAD_REQUEST )


def ranklist(clist,ll):
    clist['排名']=ll+1
    return clist